<template>
  <div class="face-wrap">
    <div class="face-txt">请用前置摄像头，正对镜头完成人脸验证</div>
    <div class="face-img">
      <img :src="face_photo == '' ? defaultPic : face_photo" />
    </div>
    <div class="face-sub-txt-wrap">
      <div class="face-sub-item">
        <img src="./../../assets/img/face_pic1.png" />
        <span>光线充足</span>
      </div>
      <div class="face-sub-item">
        <img src="./../../assets/img/face_pic2.png" />
        <span>正对手机</span>
      </div>
      <div class="face-sub-item">
        <img src="./../../assets/img/face_pic3.png" />
        <span>脸无遮挡</span>
      </div>
    </div>
    <div class="face-bottom">
      <div class="face-policy">
        <div
          @click="handleCheckToggle"
          :class="['face-circle', isChecked ? 'face-circle-active' : '']"
        >
          <svg
            v-if="isChecked"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="2620"
            width="12"
            height="12"
            xmlns:xlink="http://www.w3.org/1999/xlink"
          >
            <path
              d="M414.245926 751.028148l437.57037-453.12c7.300741-7.49037 7.111111-19.531852-0.474074-26.832593-7.49037-7.300741-19.531852-7.111111-26.832593 0.474074L398.506667 712.722963 199.111111 513.327407c-7.395556-7.395556-19.437037-7.395556-26.832593 0l0 0c-7.395556 7.395556-7.395556 19.437037 0 26.832593l212.574815 212.574815c6.731852 6.731852 17.161481 7.300741 24.557037 1.896296C411.211852 753.682963 412.823704 752.545185 414.245926 751.028148z"
              fill="#ffffff"
              p-id="2621"
            ></path>
          </svg>
        </div>
        <span @click="handlePolicy">隐私政策</span>
      </div>
      <div class="face-btn">
        <button @click="takePhoto">拍照</button>
      </div>
    </div>
  </div>
</template>

<script setup>
// import wx from 'weixin-js-sdk'
import { onMounted, reactive, toRefs, ref, watch } from 'vue'
import { postData } from '@/request/request.js'
import { showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import defaultPic from '@/assets/img/face.jpg'
let router = useRouter()
let route = useRoute()
let query = route.query
localStorage.clear()
localStorage.setItem('user_id', query.user_id)
localStorage.setItem('access_token', query.access_token)
localStorage.setItem('open_id', query.open_id)
localStorage.setItem('currentPath', query.currentPath)
localStorage.setItem('carriedUserid', query.carriedUserid || '')
let carriedUserid = route.query.carriedUserid

const face_photo = ref('')
const isChecked = ref(false)

let wxConfig = () => {
  var url = window.location.href.split('#')[0]
  postData('/wxaccess/oa/jsapi/signature', {
    url: url,
  }).then((res) => {
    wx.config({
      beta: true,
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: 'wxaa5d43496694b970', // 必填，此时是公众号的id.一致
      timestamp: res.datas.timestamp, // 必填，生成签名的时间戳
      nonceStr: res.datas.noncestr, // 必填，生成签名的随机串
      signature: res.datas.signature, // 必填，签名
      jsApiList: ['chooseImage', 'previewImage'], // 必填，需要使用的JS接口列表
      openTagList: ['wx-open-launch-weapp'], // 跳转小程序时
    })
    wx.ready(function () {
      console.log('config is success')
    })
    wx.error(function (err) {
      console.log(JSON.stringify(err))
    })
  })
}

let fn_upload = (imageBase64) => {
  let param = {}
  if (imageBase64) {
    if (carriedUserid) {
      param = {
        user_id: carriedUserid,
        image_base64: imageBase64,
        image_ext: 'jpg',
      }
    }
    postData('/user/facephoto/base64image/upload', param).then((res) => {
      if (res?.code === 0) {
        showToast('上传成功')
        if (carriedUserid) {
          // setTimeout(() => {
          //   wx &&
          //     wx.miniProgram.navigateTo({
          //       url: '/pagesC/carryUserList/carryUserList',
          //     })
          // }, 2000)
          setTimeout(() => {
            wx &&
              wx.miniProgram.navigateTo({
                url: '/pagesC/subMessage/index',
              })
          }, 2000)
        }
      } else {
        showToast('上传失败')
      }
    })
  }
}

//拍照
let takePhoto = () => {
  if (!isChecked.value) {
    showToast('请先同意隐私政策')
    return
  }
  //console.log(wx) //这个里面
  //console.log(wx.chooseMedia) //没有wx.chooseMedia,所以没法默认前置摄像头，打印它，显示undefined  是的
  wx &&
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (imgRes) => {
        let localIds = imgRes.localIds
        if (Array.isArray(localIds) && localIds.length) {
          wx &&
            wx.getLocalImgData({
              localId: localIds[0],
              success: (localImgRes) => {
                let localData = localImgRes.localData
                let imageBase64 = ''

                if (localData.indexOf('data:image') === 0) {
                  // 苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                  imageBase64 = localData
                } else {
                  // 此处是安卓中的唯一得的坑！在拼接前需要对localData进行换行符的全局替换
                  // 此时一个正常的 base64 图片路径就完美生成赋值到 img 的 src 中了
                  imageBase64 = `data:image/jpeg;base64,${localData.replace(
                    /\n/g,
                    ''
                  )}`
                }
                //console.log(imageBase64)
                face_photo.value = imageBase64
                imageBase64 && fn_upload(imageBase64)
              },
              fail: (localImgErr) => {
                console.log(localImgErr?.errMsg)
              },
            })
        }
      },
      fail: (imgErr) => {
        console.log(imgErr?.errMsg)
      },
    })
}

// 隐私政策选中
const handleCheckToggle = () => {
  isChecked.value = !isChecked.value
}

const handlePolicy = () => {
  wx &&
    wx.miniProgram.navigateTo({
      url: '/pagesC/privacyPolicy/index',
    })
}

onMounted(() => {
  wxConfig()
})

watch(
  () => route.fullPath,
  () => {
    wxConfig()
  }
)
</script>

<style scoped>
.face-wrap {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  padding-bottom: 0.84rem;
  box-sizing: border-box;
  font-size: 0.16rem;
  color: #333;
}
.face-txt {
  width: 100%;
  height: 1.04rem;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 0.14rem;
  color: #a5a5a5;
}
.face-img {
  width: 1.8rem;
  height: 1.8rem;
  margin: 0 auto;
}
.face-img img {
  width: 100%;
  height: 100%;
}
.face-sub-txt-wrap {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
}
.face-sub-item {
  width: 1.3rem;
  height: 0.82rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}
.face-sub-item img {
  width: 0.56rem;
  height: 0.56rem;
}
.face-sub-item span {
  color: #333;
  font-size: 0.14rem;
  margin-top: 0.1rem;
}
.face-bottom {
  width: 100%;
  height: 0.84rem;
  position: fixed;
  left: 0;
  bottom: 0;
  font-size: 0.14rem;
  color: #a5a5a5;
}
.face-policy {
  width: 100%;
  height: auto;
  padding: 0 0.2rem;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  box-sizing: border-box;
}
.face-policy span {
  margin-left: 0.1rem;
}
.face-circle {
  width: 0.12rem;
  height: 0.12rem;
  border: 1px solid #bcbbbb;
  border-radius: 50%;
  position: relative;
}
.face-circle-active {
  background-color: #d5ad57;
  font-size: 0.12rem;
  color: #fff;
  position: relative;
}
.face-circle-active .icon {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 0.12rem;
}
.face-btn {
  width: 100%;
  height: 0.6rem;
  box-sizing: border-box;
  padding: 0.1rem 0.16rem;
}
.face-btn button {
  width: 100%;
  height: 0.4rem;
  border-radius: 0.1rem;
  background-image: linear-gradient(to right, #ecd9b4, #d5ad57);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  outline: none;
  border: 0;
}
</style>
